package com.office.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    /**
     *
     * 该方法在目标方法之前被调用
     * 若返回值为true,则继续调用后去的拦截器和目标方法
     * 若返回值为false,则不会再调用后续的拦截器和方法
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("目标方法之前执行:preHandle");
        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser!=null){
            return true;
        }else {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("<script>alert('没有权限访问!');location.href='/';</script>");
            return false;
        }

    }


    /**
     * 目标方法调用之后，自动调用这个方法，完成后续的操作,渲染试图之前
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("目标方法之后执行:postHandle,渲染试图之前");
    }


    /**
     * 目标方法调用之后，自动调用这个方法，完成后续的操作,渲染试图之后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("目标方法之后执行:postHandle,渲染试图之后");
    }
}
